<template>
    <div class="page-container">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="车牌号" prop="plateNumber">
          <el-input
            v-model="queryParams.plateNumber"
            placeholder="请输入车牌号"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input
            v-model="queryParams.brand"
            placeholder="请输入品牌"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['customer:vehicle:add']"
            >新增车辆</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['customer:vehicle:remove']"
            >批量删除</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
          :columns="columns"
        ></right-toolbar>
      </el-row>
  
      <el-table
        v-loading="loading"
        :data="vehicleList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          label="ID"
          align="center"
          key="id"
          prop="id"
          v-if="columns[0].visible"
        />
        <el-table-column
          label="所属用户"
          align="center"
          key="customerId"
          prop="customers.name"
          v-if="columns[1].visible"
        />
        <el-table-column
          label="车牌号"
          align="center"
          key="plateNumber"
          prop="plateNumber"
          v-if="columns[2].visible"
        />
        <el-table-column
          label="品牌"
          align="center"
          key="brand"
          prop="brand"
          v-if="columns[3].visible"
        />
        <el-table-column
          label="型号"
          align="center"
          key="model"
          prop="model"
          v-if="columns[4].visible"
        />
        <el-table-column
          label="颜色"
          align="center"
          key="color"
          prop="color"
          v-if="columns[5].visible"
        />
        <el-table-column
          label="年份"
          align="center"
          key="year"
          prop="year"
          v-if="columns[6].visible"
        />
        <el-table-column
          label="默认车辆"
          align="center"
          key="isDefault"
          prop="isDefault"
          v-if="columns[7].visible"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.isDefault === 1 ? 'success' : 'info'">
              {{ scope.row.isDefault === 1 ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="180"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['customer:vehicle:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['customer:vehicle:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改车辆对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="车牌号" prop="plateNumber">
            <el-input v-model="form.plateNumber" placeholder="请输入车牌号" />
          </el-form-item>
          <el-form-item label="品牌" prop="brand">
            <el-input v-model="form.brand" placeholder="请输入品牌" />
          </el-form-item>
          <el-form-item label="型号" prop="model">
            <el-input v-model="form.model" placeholder="请输入型号" />
          </el-form-item>
          <el-form-item label="颜色" prop="color">
            <el-input v-model="form.color" placeholder="请输入颜色" />
          </el-form-item>
          <el-form-item label="年份" prop="year">
            <el-date-picker
              v-model="form.year"
              type="year"
              placeholder="选择年份"
              value-format="yyyy"
              format="yyyy"
              :clearable="false"
            />
          </el-form-item>
          <el-form-item label="默认车辆" prop="isDefault">
            <el-switch
              v-model="form.isDefault"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import {
    listVehicles,
    getVehicle,
    addVehicle,
    updateVehicle,
    deleteVehicle,
    deleteVehicles,
  } from "@/api/customer/vehicle";
  
  export default {
    name: "Vehicle",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 车辆列表数据
        vehicleList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          plateNumber: undefined,
          brand: undefined,
        },
        // 列信息
        columns: [
          { key: 0, label: `ID`, visible: true },
          { key: 1, label: `所属用户`, visible: true },
          { key: 2, label: `车牌号`, visible: true },
          { key: 3, label: `品牌`, visible: true },
          { key: 4, label: `型号`, visible: true },
          { key: 5, label: `颜色`, visible: true },
          { key: 6, label: `年份`, visible: true },
          { key: 7, label: `默认车辆`, visible: true },
        ],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {
          id: undefined,
          customerId: undefined,
          plateNumber: undefined,
          brand: undefined,
          model: undefined,
          color: undefined,
          year: '',
          isDefault: 0,
        },
        // 表单校验
        rules: {
          plateNumber: [
            { required: true, message: "车牌号不能为空", trigger: "blur" },
            {
              pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{4,5}[A-Z0-9挂学警港澳]$/,
              message: "请输入正确的车牌号",
              trigger: "blur",
            },
          ],
          brand: [
            { required: true, message: "品牌不能为空", trigger: "blur" },
          ],
          model: [
            { required: true, message: "型号不能为空", trigger: "blur" },
          ],
          color: [
            { required: true, message: "颜色不能为空", trigger: "blur" },
          ],
          year: [
            { required: true, message: "年份不能为空", trigger: "blur" },
          ],
        },
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询车辆列表 */
      getList() {
        this.loading = true;
        listVehicles(this.queryParams)
          .then((response) => {
            this.vehicleList = response.rows || [];
            this.total = Number(response.total) || 0;
          })
          .catch(() => {
            this.$modal.msgError("获取车辆列表失败");
            this.vehicleList = [];
            this.total = 0;
          })
          .finally(() => {
            this.loading = false;
          });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加车辆";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids[0];
        if (!id) {
          this.$modal.msgError("获取车辆ID失败");
          return;
        }
        getVehicle(id).then((response) => {
          this.form = response;
          this.open = true;
          this.title = "修改车辆";
        }).catch((error) => {
          this.$modal.msgError(error.msg || "获取车辆信息失败");
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.id) {
              updateVehicle(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addVehicle(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const vehicleIds = row.id || this.ids;
        this.$modal
          .confirm("是否确认删除选中的车辆数据？")
          .then(() => {
            if (row.id) {
              return deleteVehicle(row.id);
            } else {
              return deleteVehicles(this.ids.join(","));
            }
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      },
      /** 取消按钮 */
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          customerId: undefined,
          plateNumber: undefined,
          brand: undefined,
          model: undefined,
          color: undefined,
          year: '',
          isDefault: 0,
        };
        this.resetForm("form");
      },
    },
  };
  </script>
  
  <style>
  .page-container {
    margin-top: 20px;
    padding: 0 20px;
  }
  
  .mb8 {
    margin-bottom: 8px;
  }
  
  .el-table .cell {
    white-space: nowrap;
  }
  
  .el-form-item__label {
    font-weight: bold;
  }
  
  .el-dialog__body {
    padding: 20px 30px;
  }
  </style>
  